<?php

namespace App\Controller\Api\User;

use App\Constants\ErrorCode;
use App\Controller\Api\BaseController;
use App\Helper\CommonHelper;
use App\Model\ConsultantDatum;
use App\Model\EvaluationLog;
use App\Model\LoginLog;
use App\Model\PsychologicalAssessment;
use App\Model\SearchHotlist;
use App\Model\User;
use App\Model\UserBlacklist;
use App\Model\UserDatum;
use App\Model\UserFeedbackLog;
use App\Model\UserFollow;
use App\Model\UserReportLog;
use App\Support\AwsS3;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Middleware\JWTAuthMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;

/**
 * @Middleware(JWTAuthMiddleware::class)
 * @Controller(prefix="/user/v1/user")
 */
class UserController extends BaseController
{


    /**
     * 设置用户基本信息
     * @RequestMapping(path="setUserDatum")
     */
    public function setUserDatum()
    {

        $params = $this->request->post();

        $this->validate($params, [
            'gender' => "required",
            'nickname' => 'required',
            'birthday' => 'required',
            'country' => 'required'

        ]);


        $updateData = [
            'gender' => $params['gender'],
            'birthday' => $params['birthday'],
            'head' => $params['head'] ?? '',
            'confusion_id' => $params['confusionId'],
            'nickname' => $params['nickname'],
            'country' => $params['country'] ?? 0,
            'language' => $params['language'] ?? 0,
            'status' => 1,
            'update_time' => time()
        ];

        $rel = UserDatum::where(['uid' => $this->uid()])->update($updateData);

        if ($rel) {
            $userRedisKey = 'user:userinfo:' . $this->uid();
            cache()->delete($userRedisKey);
            $info = UserDatum::userInfo($this->uid());
            return $this->response->returnSuccess($info);
        } else {
            return $this->response->returnFail();
        }

    }


    /**
     * 用户修改信息基本信息
     * 缓存--user:userinfo:
     * @RequestMapping(path="userDatumInfo")
     * @return ResponseInterface
     * @throws InvalidArgumentException
     */
    public function userDatumInfo()
    {

        $uid = $this->uid();

        $info = UserDatum::userInfo($uid);


        return $this->response->returnSuccess($info);

    }


    /**
     * 个人中心接口 增加
     * @RequestMapping(path="personalCenter")
     * @return ResponseInterface
     */
    public function personalCenter()
    {


        $info = User::where(['id' => $this->uid()])->select(['nickname', 'num']);

        $info = User::from('user as a')
            ->leftJoin('user_datum as b', 'a.id', '=', 'b.uid')
            ->select(['a.num', 'b.head', 'b.nickname','a.role','a.become_due as becomeDue'])
            ->where(['a.id' => $this->uid()])
            ->first();

        if (!$info) {
            return $this->response->returnFail();
        }
        $info['follow'] = '14';
        $info['collection'] = '15';
        $info['evaluation'] = '16';

        return $this->response->returnSuccess(['info' => $info]);


    }


    /**
     * 心理评测列表
     * @RequestMapping(path="evaluatingList")
     * @return ResponseInterface
     */
    public function evaluatingList()
    {


        $list = PsychologicalAssessment::getEvaluatingList();

        return $this->response->returnSuccess(['list' => $list]);


    }


    /**
     *访问心理评测
     * @RequestMapping(path="accessEvaluating")
     */
    public function accessEvaluating()
    {

        $id = $this->request->query('id');

        $charge = PsychologicalAssessment::where(['id' => $id])->value('charge');
        if (is_null($charge)) {
            return $this->response->returnFail(ErrorCode::ERROR);
        }


        // 后期可以考虑做成后期配置
        $num = 1;

        if ($charge == 1) {
            $num = 3;
        }

        PsychologicalAssessment::where(['id' => $id])->increment('hot', $num);


        return $this->response->returnSuccess();

    }


    /**
     * 咨询师搜索
     * @RequestMapping(path="search")
     */
    public function search()
    {

        $params = $this->request->query();

        $this->validate($params, [
            'keyword' => "required",
            'type' => "required"
        ]);

        SearchHotlist::addHot($params['keyword']);

        $list = null;
        switch ($params['type']) {
            case 1://搜索咨询
                $list = ConsultantDatum::searchConsultantList($params['keyword']);
                break;
            case 2:
                $list = PsychologicalAssessment::searchEvaluatingList($params['keyword']);
                break;
        }


        return $this->response->returnSuccess(['list' => $list]);


    }


    /**
     * 用户反馈
     * @RequestMapping(path="feedback")
     */
    public function feedback()
    {

        $params = $this->request->post();

        $this->validate($params, [
            'description' => 'required',
            'type' => 'required'
        ]);


        $insertData = [
            'type' => $params['type'] ?? '',
            'description' => $params['description'] ?? '',
            'url' => $params['url'] ?? '',
            'uid' => $this->uid(),
            'create_time' => time()
        ];
        $rel = UserFeedbackLog::insert($insertData);
        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }

    }


    /**
     * 注销账号
     * @RequestMapping(path="logOff")
     * @return ResponseInterface
     */
    public function logOff()
    {
        $uid = $this->uid();


        // todo 后期增加处理环信 账号注销 声望账户注销/下线等其他第三方操作
        redis()->del('user:userToken:' . $uid);
        $rel = User::where(['id' => $uid])->update(['status' => 0, 'deleted_time' => time()]);

        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }

    }


    /**
     * @RequestMapping(path="logout")
     * @return ResponseInterface
     */
    public function logout()
    {

        $uid = $this->uid();

        // todo 后期增加处理环信 账号注销 声望账户注销/下线等其他第三方操作
        redis()->del('user:userToken:' . $uid);
        return $this->response->returnSuccess();
    }


    /**
     * 上传图片
     * @RequestMapping(path="getAwsPresagedUrl")
     */
    public function getAwsPresagedUrl()
    {
        $aws = new AwsS3();

        $file = $this->request->post('file');
        $ext = explode('/', $file)[1] ?? 'jpg';

        $pathDev = config('app_env') == 'dev' ? 'dev/' : '';
        $path = 'listener/' . $pathDev . date('Y-m-d') . '/' . CommonHelper::imgName() . '.' . $ext;
        $cdnurl = env('IMG_URL') . '/' . $path;
        $url = $aws->getPresagedUrl($path);

        return $this->response->returnSuccess(['url' => $url, 'cdnUrl' => $cdnurl]);


    }


    /**
     * 系统参数信息
     * @RequestMapping(path="sysSettingInfo")
     * @return ResponseInterface
     */
    public function sysSettingInfo()
    {
        $data = [
            'registerConsultantUrl' => 'https://h5.soulcare.plus/consultant',//注册咨询师地址
            'helpCenterUrl' => 'https://h5.soulcare.plus/helpCenter',// 帮助中心地址
        ];

        return $this->response->returnSuccess($data);
    }


    /**
     * 我的关注列表
     * @RequestMapping(path="myFollowList")
     */
    public function myFollowList()
    {

        $list = UserFollow::getFollowList($this->uid());

        return $this->response->returnSuccess(['list' => $list]);

    }


    /**
     * 关注&取消关注
     * @RequestMapping(path="followWithConsultant")
     * @return ResponseInterface
     */
    public function followWithConsultant()
    {

        $aid = $this->request->post('uid', 0);

        if ($aid == $this->uid() || empty($aid)) {
            return $this->response->returnFail();
        }

        $rel = UserFollow::followWith($this->uid(), $aid);

        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }


    }


    /**
     * @RequestMapping(path="tokenRefresh")
     * @return ResponseInterface
     * @throws InvalidArgumentException
     */
    public function tokenRefresh()
    {

        $lastLogin = LoginLog::where(['uid' => $this->uid()])->orderBy('id', 'desc')->first();
        if (is_null($lastLogin)) {
            return $this->response->returnFail();
        }

        $user = User::jwtLoginInfo($this->uid());
        if (!is_null($user)) {
            try {
                if (is_object($user)){
                    $token = auth('jwt')->login($user);
                }else{
                    $token = auth('jwt')->login((object)$user);
                }
                // 加入登录名单
                redis()->set('user:userToken:' . $this->uid(), $token);


                //记录登录信息
                LoginLog::addLoginLog($this->uid(), $lastLogin['login_account'], $lastLogin['platform'], 2);


                return $this->response->returnSuccess([
                    'token' => $token,
                    'userInfo' => UserDatum::userInfo($this->uid())
                ]);
            } catch (\Exception $exception) {
                recordExceptionLog('登录JWT失败', $exception->getMessage());
                return $this->response->returnFail();
            }
        } else {
            return $this->response->returnFail();
        }

    }


    /**
     * @RequestMapping(path="myEvaluationList")
     * @return ResponseInterface
     */
    public function myEvaluationList()
    {

        $list = EvaluationLog::getMyEvaluationList($this->uid());

        return $this->response->returnSuccess(['list' => $list]);


    }


    /**
     * 我的黑名单
     * @RequestMapping(path="myBlackList")
     * @return ResponseInterface
     */
    public function myBlackList()
    {

        $list = UserBlacklist::getMyBlackList($this->uid());

        return $this->response->returnSuccess(['list' => $list]);

    }


    /**
     * 加入黑名单
     * @RequestMapping(path="addBlackList")
     * @return ResponseInterface
     */
    public function addBlackList()
    {


        $params = $this->request->post();
        $blackId = $this->request->post('uid');

        $this->validate($params, [
            'uid' => 'required'
        ]);

        $exists = UserBlacklist::where(['uid' => $this->uid(), 'blacked_uid' => $blackId])->exists();
        if ($exists) {
            return $this->response->returnSuccess();
        }

        $insertData = [
            'uid' => $this->uid(),
            'blacked_uid' => $blackId,
            'create_time' => time()
        ];
        $rel = UserBlacklist::insert($insertData);

        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();

        }

    }


    /**
     *移除黑名单
     * @RequestMapping(path="removeBlack")
     * @return ResponseInterface
     * @throws \Exception
     */
    public function removeBlack()
    {
        $params = $this->request->post();
        $blackId = $this->request->post('uid');
        $this->validate($params, [
            'uid' => 'required'
        ]);

        $info = UserBlacklist::where(['uid' => $this->uid(), 'blacked_uid' => $blackId])->first();
        if (!is_null($info)) {
            $info->delete();
        }
        return $this->response->returnSuccess();
    }


    /**
     * @RequestMapping(path="reportConsultant")
     */
    public function reportConsultant()
    {

        $params = $this->request->post();

        $this->validate($params, [
            'uid' => 'required',
            'rid' => 'required'
        ]);


        $insertData = [
            'uid' => $this->uid(),
            'rid' => $params['rid'],
            'type' => 2,
            'status' => 0,
            'report_uid' => $params['uid'],
            'create_time' => time()
        ];

        $rel = UserReportLog::insert($insertData);

        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }

    }





}
